package GameObject;

import Global.ResourceManager;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class Sprite extends ImageObject {

	private int nRow;
	private int nCol;
	private int frame;
	private int[] sequence;

	private void init(int x, int y, int w, int h, int col, int row) {
		width = w;
		height = h;
		nRow = row;
		nCol = col;
		position = new Point(x, y);
		innerPoint = new Point(0, 0);
		frame = 0;
		scaleX = 1;
		scaleY = 1;
	}

	public boolean isLastFrame() {
		if (sequence != null && sequence.length > frame) {
			return frame == sequence.length - 1;
		}
		return true;
	}

	public Sprite(String res, int col, int row) throws IOException {
		bufferImg = ResourceManager.getImage(res);
		init(0, 0, bufferImg.getWidth() / col, bufferImg.getHeight() / row, col, row);
	}

	public Sprite(BufferedImage res, int col, int row, int x, int y) {
		bufferImg = res;
		init(x, y, bufferImg.getWidth() / col, bufferImg.getHeight() / row, col, row);
	}

	public void setSequence(int[] s) {
		frame = 0;
		sequence = s;
	}

	public void setSequence(int start, int n) {
		sequence = new int[n];
		for (int i = 0; i < n; i++) {
			sequence[i] = i + start;
		}
		frame = 0;
	}

	public void setSequence(int start) {
		int n = nCol * nRow;
		setSequence(start, n);
	}

	public void setFrame(int f) {
		frame = f;
	}

	public int getFrame() {
		if (sequence != null && sequence.length > frame) {
			return sequence[frame];
		}
		return frame;
	}

	public void nextFrame() {
		if (sequence != null && sequence.length > 0) {
			frame = (frame + 1) % sequence.length;
		}
	}

	public void previousFrame() {
		if (sequence.length == 0) {
			return;
		}

		frame--;
		if (frame < 0) {
			frame = sequence.length - 1;
		}

	}

	@Override
	public void draw(Graphics2D g,int dx,int dy) {

		Point p = transform(g,dx,dy);
		int x = p.x;
		int y = p.y;

		int f = frame;
		if (sequence != null && sequence.length > 0) {
			f = sequence[frame];
		}
		int i = f / nCol;
		int j = f % nCol;
		g.drawImage(bufferImg,
				x, y, x + (int) (width * scaleX), y + (int) (height * scaleY),
				j * width, i * height, (j + 1) * width, (i + 1) * height, null);
		// g.drawRect(x, y, width, height);

	}

	
}
